var mongoose = require('mongoose'),
    PublicFun = require('./Function'),
    PublicEnum = require('./Enum'),
    entityCollection = require('./EntityCollection'),
    Transaction = require('./Transaction'),
    User = mongoose.model('User'),
    formidable = require("formidable");

//单个保存文档，根据有无_id值判断是否新增还是修改
//返回值：当前被保存的文档
exports.save = function(req, res) {
    //PublicFun.authorizedCheck(req.user, res);

    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);
    var records = parameter.Records;
    for (var i = 0; i < records.length; i++) {
        if (records[i].RowStatus == PublicEnum.RowStatus.Insert) {
            records[i].CreatedBy = req.user._id;
        } else if (records[i].RowStatus == PublicEnum.RowStatus.Modify) {
            records[i].ModifyBy = req.user._id;
        }
    }

    entity.save(records, PublicFun.responseHandler(res));
};
//批量保存文档，根据有无_id值判断是否新增还是修改
//返回值：当前被保存的文档集合
exports.saves = function(req, res) {
    PublicFun.authorizedCheck(req.user, res);

    var parameter = req.body.Parameter;
    var entityRecords = parameter.EntityRecords;

    for (var i = 0; i < parameter.EntityRecords.length; i++) {
        for (var j = 0; j < parameter.EntityRecords[i].Records.length; j++) {
            if (parameter.EntityRecords[i].Records[j].RowStatus == PublicEnum.RowStatus.Insert) {
                parameter.EntityRecords[i].Records[j].CreatedBy = req.user._id;
            } else if (parameter.EntityRecords[i].Records[j].RowStatus == PublicEnum.RowStatus.Modify) {
                parameter.EntityRecords[i].Records[j].ModifyBy = req.user._id;
            }
        }
    }

    Transaction.BatchSaveByTran(entityRecords, PublicFun.responseHandler(res));
};

exports.updateByValue = function(req, res) {
    PublicFun.authorizedCheck(req.user, res);

    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.updateByValue(parameter.Condition, parameter.Value, PublicFun.responseHandler(res));
};

//按条件删除文档
//返回值：删除的条数
exports.delete = function(req, res) {
    PublicFun.authorizedCheck(req.user, res);

    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.delete(parameter.Condition, PublicFun.responseHandler(res));
};
//按多个条件遍历批量删除文档
//返回值：删除的条数
exports.deletes = function(req, res) {
    PublicFun.authorizedCheck(req.user, res);

    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);
    var conditions = parameter.Conditions;
    var result = 0;
    var isErr = false;

    var callbackFun = function(err, result) {
        if (err) {
            isErr = true;
        }
        result++;
        if (result == conditions.length) {
            if (isErr) {
                var newErr = new Error();
                newErr.leval = 5;
                newErr.title = '删除失败';
                newErr.message = '删除失败，请重试';

                res.status(400).send(newErr);
                res.end();
            } else {
                res.json({ Data: true });
            }
        }
    };

    for (var condition in conditions) {
        entity.delete(condition, callbackFun);
    }
};
//按_id单个删除文档
//返回值：删除的条数
exports.deleteById = function(req, res) {
    PublicFun.authorizedCheck(req.user, res);

    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.deleteById(parameter.ID, PublicFun.responseHandler(res));
};
//按_id集合批量删除文档
//返回值：删除的条数
exports.deleteByIds = function(req, res) {
    PublicFun.authorizedCheck(req.user, res);

    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.deleteByIds(parameter.IDs, PublicFun.responseHandler(res));
};


//按条件查找文档
//返回值：所有符合条件的文档
exports.find = function(req, res) {
    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);

    //entity.Entity.schema.paths.CreatedOn.options.type == Date 获取字段类型样例
    var condition = parameter.Condition;
    entity.find(condition, parameter.OrderBy, parameter.Populate, PublicFun.responseHandler(res));
};
//按_id查找文档
//返回值：当前_id所对应的文档
exports.findById = function(req, res) {
    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.findById(parameter.ID, parameter.Populate, PublicFun.responseHandler(res, 0, '参数传输错误提示'));
};
//按条件查找文档是否存在
//返回值：满足条件的第一个文档
exports.findOne = function(req, res) {
    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.findOne(condition, parameter.Populate, PublicFun.responseHandler(res));
};

exports.search = function(req, res) {
    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);
    if (parameter.Condition == undefined) {
        parameter.Condition = null;
    }
    if (parameter.Limit == undefined) {
        parameter.Limit = null;
    }

    entity.search(parameter.Text, parameter.Condition, parameter.Limit, PublicFun.responseHandler(res));
    //entity.collection.command("text", {search: "phrase"});
    //this.db.command({text:"collection" , search: "phrase" }).
    //‌‌this.Entity.db.db.executeDbCommand
    //‌‌this.Entity.db.db.executeDbCommand({text:"Department" , search: "vt" },function(err, res){Console.log(err.toString() + res.toString())})
};

//20160225模糊查询
exports.queryByKeyword = function(req, res) {
    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);
    var condition = parameter.Condition;
    var queryCondition = {};
    var arrayObj = new Array();
    for (var item in condition) {
        var tempCondition = {};
        tempCondition[item] = new RegExp(condition[item]);
        arrayObj.push(tempCondition);
    }
    queryCondition["$or"] = arrayObj;
    entity.find(queryCondition, parameter.OrderBy, parameter.Populate, PublicFun.responseHandler(res));
};


//根据条件查找满足条件的该文档所在条件集合的索引位置，为翻页功能提供
//返回值：当前满足条件的文档所对应的索引位置
exports.findRecordIndex = function(req, res) {
    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);

    entity.findRecordIndex(parameter.ID, parameter.Condition, parameter.OrderBy, PublicFun.responseHandler(res, 0, '参数传输错误提示'));
};
//查找某一页的全部文档
//返回值：该页的全部文档
exports.pageQuery = function(req, res) {
    var parameter = req.body.Parameter;

    var entity = entityCollection.getEntity(parameter.EntityName);
    var queryParameter = parameter.QueryParameter;
    entity.pageQuery(queryParameter.Condition, queryParameter.OrderBy,
        queryParameter.Populate, queryParameter.PageNum, queryParameter.PageSize,
        PublicFun.responseHandler(res)
    );
};
//查找满足条件的文档个数
//返回值：满足条件的文档个数
exports.queryRecordCount = function(req, res) {
    var parameter = req.body.Parameter;
    var entity = entityCollection.getEntity(parameter.EntityName);
    entity.queryRecordCount(parameter.Condition, PublicFun.responseHandler(res));
};

//通过编码查找扩展枚举
exports.getExtendEnum = function(req, res){
    var enumCode = req.body.Parameter.Code;
    var entity = entityCollection.getEntity("ExtendEnum");
    entity.findOne({Code: enumCode}, null, function(err, record){
        if(err){
            var newErr = new Error();
            err.leval = 9;
            err.title = '系统查询错误';
            err.message = '通过编码查询扩展枚举失败，请检查查询条件';
            res.status(400).send(err);
        }
        else {
            if(record != null){
                var extendEnum = {};
                for(var i=0; i<record.Options.length; i++){
                    extendEnum["Enum" + i.toString()] = {
                        Value: record.Options[i].Value, 
                        Text: record.Options[i].Name
                    }
                }
                res.json({Data: extendEnum});
            }
            else{
                res.json({Data: null});
            }
        }
    });
};

exports.getSysParameterValue = function(req, res){
    var code = req.body.Parameter.Code;
    var entity = entityCollection.getEntity("Parameter");
    entity.findOne({Code: code}, null, function(err, record){
        if(err){
            var newErr = new Error();
            err.leval = 9;
            err.title = '系统查询错误';
            err.message = '通过编码查询系统参数失败，请检查查询条件';
            res.status(400).send(err);
        }
        else {
            if(record != null){
                var value;
                if(record.Type == PublicEnum.ControlType.TextBox){
                    value = record.Value;
                }
                else if(record.Type == PublicEnum.ControlType.CheckBox){
                    if(record.Value == 'true'){
                        value = true;
                    }
                    else{
                        value = false;
                    }
                }
                else if(record.Type == PublicEnum.ControlType.NumberBox){
                    value = parseFloat(record.Value);
                }
                else if(record.Type == PublicEnum.ControlType.PercentBox){
                    value = parseFloat(record.Value);
                }
                else if(record.Type == PublicEnum.ControlType.DropDownList){
                    value = parseInt(record.Value);
                }
                else if(record.Type == PublicEnum.ControlType.Refer){
                    value = {
                        Key: record.Key,
                        Value: record.Value,
                        Text: record.Text
                    };
                }
                else if(record.Type == PublicEnum.ControlType.Calendar){
                    if(record.CalendarType == PublicEnum.DateTimeFormat.Date){
                        var date = new Date(record.Value);
                        value = new Date(date.getFullYear(), date.getMonth(), date.getDate());
                    }
                    else{
                        value = new Date(record.Value);
                    }
                }
                res.json({Data: value});
            }
            else{
                res.json({Data: null});
            }
        }
    });
};

exports.fileUpload = function(req, res) {

    var reviceData = {};
    var form = new formidable.IncomingForm();
    form.uploadDir = './public/users/img/'; //上传目录
    form.keepExtensions = true; //保留后缀格式
    form.maxFieldsSize = 2 * 1024 * 1024; //文件大小

    form.on('error', function() {
        res.status(400).send({
            message: "文件解析错误"
        });
        res.json({
            message: "文件解析错误"
        });
    });

    form.on('field', function(name, value) {
        reviceData[name] = value;
    });

    form.on('file', function(name, file) {
        reviceData[name] = file;
    });

    form.on('progress', function(bytesReceived, bytesExpected) {
        var progress = {
            type: 'progress',
            bytesReceived: bytesReceived,
            bytesExpected: bytesExpected,
            uploadProgress: bytesExpected / req.headers['content-length']
        };

        reviceData['progress'] = progress.uploadProgress * 100 + '%';
    });

    form.on('end', function() {
        var str = reviceData['file'].path.replace(/\\/g, "/");
        var strArr = str.split('/');
        res.status(200).send({
            path: strArr[1] + '/' + strArr[2] + '/' + strArr[3],
            fullPath: reviceData['file'].path
        });
    });
    form.parse(req);
};
